package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;

import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.query.JsonResult;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    // 查询所有请求信息
    //@RequiresPermissions(value = {"employee:list","员工列表"},logical = Logical.OR)
    //@RequiredPermission(name = "员工列表",expression = "employee:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo){

        // 获取用户主体
        Subject subject = SecurityUtils.getSubject();
        // 判断用户主体角色是否有权限,底层会调用 数据源 realm 获取 subject 所拥有的权限和角色信息
        System.out.println(subject.hasRole("HR"));
        System.out.println(subject.isPermitted("employee:save"));

        PageInfo<Employee> pageResult = employeeService.query(qo);
        model.addAttribute("result",pageResult);
        model.addAttribute("departments",departmentService.listAll());
        return "employee/list";
    }

    // 删除信息
    @RequiredPermission(name = "员工删除",expression = "employee:delete")
    @RequestMapping("/delete")
    @ResponseBody // 响应 JSON 使用  @ResponseBody 注解
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                employeeService.delete(id);
                return new JsonResult(true,"删除成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(true,"删除失败");
    }

    // 批量删除信息
    @RequestMapping("/deleteAll")
    @ResponseBody // 响应 JSON 使用  @ResponseBody 注解
    public JsonResult deleteAll(Long[] ids){
            if (ids != null) {
                employeeService.deleteALL(ids);
                return new JsonResult(true,"删除成功");
            }
        return new JsonResult(true,"删除失败");
    }

    // 跳转到添加页面
    @RequiredPermission(name = "员工添加",expression = "employee:input")
    @RequestMapping("/input")
    public String input(Model model,Long id){
        model.addAttribute("departments",departmentService.listAll());
        model.addAttribute("roles",roleService.listAll());
        // 如果 id 不为空,携带该 id 对应的数据过 input 视图
        if (id != null) {
            model.addAttribute("employee",employeeService.get(id));
        }
        // 跳转到 input 视图
        return "employee/input";
    }

    // 跳转到修改密码页面
    @RequestMapping("/updatePassword")
    public String updatePassword(){
        return "employee/updatePwd";
    }

    // 修改密码
    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String newPassword){
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        //System.out.println(employee.getId());
        if (newPassword!=null && employee!=null){
            employeeService.updatePwd(employee.getId(),newPassword);
            return new JsonResult(true,"修改密码成功");
        }
        return new JsonResult(false,"修改密码失败");
    }

    // 添加 或 修改 信息
    @RequiredPermission(name = "员工添加或修改",expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee,Long ids[]){
        if (employee.getId() != null) {
            // 如果 id 不为空,调用 修改方法
            employeeService.update(employee,ids);
        }else {
            Md5Hash md5Hash = new Md5Hash(employee.getPassword());
            employee.setPassword(md5Hash.toString());
            // 如果 id 为空,调用保存方法
            employeeService.save(employee,ids);
        }
        return new JsonResult(true,"操作成功");
    }


    // 判断用户名是否存在
    @RequestMapping("/checkName")
    @ResponseBody
    public Map checkName(String name,Long id){
        // 根据传过来的 id 查询用户名是否和当前用户名相等,
        // 相等则不验证,返回 false
        // 如果 employee 为空,则表示用户名通过,返回 true
        return  employeeService.checkByName(name,id);
    }

    // 判断密码是否和原密码一致
    @RequestMapping("/checkPwd")
    @ResponseBody
    public Map checkPwd(String oldPassword){
        HashMap<String, Boolean> map = new HashMap<>();
        // 根据传过来的 id 查询用户名的密码是否和原密码相等,
        // 相等则不验证,返回 false
        // 如果 employee 为空,则表示用户名通过,返回 true
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if (oldPassword.equals(employee.getPassword())){
            map.put("valid",true);
        }
        return  map;
    }

    // 实现导出文件
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        // 设置文件下载的响应头信息
        String filename = "exportXls.xls";
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        // 调用 service 层的方法创建一个工作簿
        Workbook sheets = employeeService.exportXls();
        // 流对象写出去
        sheets.write(response.getOutputStream());
    }

    // 导入文件
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(Part file) throws Exception {
       /* String header = file.getHeader("Content-Disposition");
        String substring = header.substring(header.lastIndexOf("."), header.length() - 1);
        System.out.println("切割后的文件名:" + substring);
        System.out.println("文件名:"+file.getName());
        System.out.println("文件类型:"+file.getContentType());*/
        employeeService.importXls(file);
        return new JsonResult(true,"上传成功");
    }

    // 修改用户状态
    @RequestMapping("/updateStatus")
    @ResponseBody
    public JsonResult updateStatus(Long id,boolean status){
        if (id != null){
            employeeService.updateStatus(id,status);
        }
        return new JsonResult(true,"操作成功");
    }
}
